package com.starblink.product.detail.postrecommend

import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.BarUtils
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.UserRelationCodeEnum
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.util.post.PostUtils
import com.starblink.android.common.R
import com.starblink.android.common.utils.PostDetailHelp
import com.starblink.android.common.view.decoration.SpaceItemDecoration
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.autosize.utils.AutoSizeUtils.dp2px
import com.starblink.basic.ext.appScreenHeight
import com.starblink.basic.ext.contentViewHeight2
import com.starblink.basic.ext.screenHeight
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.view.indicator.GuangDrawableIndicator
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.ScreenUtils
import com.starblink.comment.ui.CommentPostListDialog
import com.starblink.product.databinding.ItemMountProductBinding
import com.starblink.product.databinding.ItemRecommendPostDetailBinding
import com.starblink.product.detail.adapter.ProductImgAdapter
import com.starblink.product.detail.postrecommend.data.PicPost
import com.starblink.product.view.MountedProductHolder
import com.starblink.rocketreserver.fragment.PostD
import com.starblink.rocketreserver.fragment.Poster
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.youth.banner.config.IndicatorConfig
import com.youth.banner.listener.OnPageChangeListener


class RecommendPostDetailHolder(
    binding: ItemRecommendPostDetailBinding,
    val activity: AppCompatActivity,
    val list: ArrayList<Any>,
    val traceId: String = "",//
    val pageTrackTag: String = "",//
    val shareCallBack: () -> Unit,
) :
    BaseBindingVH<PicPost, ItemRecommendPostDetailBinding>(binding = binding) {
    var hasNext: Boolean = true

    var index: Int = 0
    var currentImgUrl: String? = ""//当前展示图片 用于识图
    var hasShowed: Boolean = false//是否已初始化过

    override fun onBind(post: PicPost, position: Int) {
        itemView.tag = post
        index = position
        currentImgUrl = post.mainPic
        hasNext = position < list.size - 1


        itemView.trackData(
            page = SpmPageDef.SimilarProductListPage,
            element = SpmElementDef.DetailContent,
            traceInfo = post.traceInfo,
            params = SpmTrackHandler.trackPostMap(
                position,
                post.toJson().toBean<PostD>()
            ),
            showRatio = 0.9f,
            businessSuffixID = businessSuffixId(post)
        )

        val lp: ConstraintLayout.LayoutParams =
            binding.llContent.layoutParams as ConstraintLayout.LayoutParams

        if (position < 3 && hasNext) {
            var containerH = activity.contentViewHeight2
            containerH -= dp2px(62f)//存在引导
            lp.bottomMargin = 24.dp
            binding.container2.updateLayoutParams {
                width = ViewGroup.LayoutParams.MATCH_PARENT
                height = containerH
            }
        } else {
            binding.container2.updateLayoutParams {
                width = ViewGroup.LayoutParams.MATCH_PARENT
                height = ViewGroup.LayoutParams.MATCH_PARENT
            }
            lp.bottomMargin = 10.dp
        }
        binding.llContent.layoutParams = lp


        setLayoutSize(post, position)

        showLikeCommentView(
            activity, post, binding.tvComment, binding.tvShare, binding.tvLike,
            binding.ivComment, binding.ivLike, position
        )

        PostDetailHelp.showPostUser(
            activity,
            post.posterInfo,
            binding.ivUser,
            binding.tvName,
            needAt = true
        )

        setFollowState(post.posterInfo.poster.relationCode)

//        PostDetailHelp.showTopicView(activity, post, binding.flTopic)

        if (post.content != null) {
//        if (post.content != null && post.content!!.isNotEmpty()) {
            binding.llContent.visibleOrGone(true) {}
            ///内容标题+用户话题
            binding.tvTitle.visibility = View.VISIBLE
            val viewWidth: Int = ScreenUtils.getScreenWidth(activity) - dp2px(activity, 48f)
            binding.tvTitle.initWidth(viewWidth)
            binding.tvTitle.maxLines = 2
            binding.tvTitle.setHasAnimation(true)
            binding.tvTitle.setNeedOpen(false)
            binding.tvTitle.setCloseInNewLine(false)
            binding.tvTitle.setOpenSuffixColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray400))
            binding.tvTitle.setCloseSuffixColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_gray400))

            binding.tvTitle.setOriginalText(
                post.content ?: ""
            )

            binding.tvTitle.setOnClickListener {
                PostContentDetailDialog(activity, post).show(
                    activity.supportFragmentManager,
                    "post_detail"
                )
            }
        } else {
            binding.llContent.visibleOrGone(false) {}
        }

        showMountedProduct(post, binding.llProduct, binding.recycler)

        setListener(post, position)

    }

    /**
     * 点赞 评论 分享等信息
     */
    fun showLikeCommentView(
        activity: FragmentActivity,
        post: PicPost,
        tvComment: TextView,
        tvShare: TextView,
        tvLike: TextView,
        ivComment: ImageView,
        ivLike: ImageView,
        position: Int,
    ) {
        tvComment.text = if (post.commentCount == 0) "" else post.commentCount.toString()
        tvShare.text = if (post.shareCount == 0) "" else post.shareCount.toString()

        if (post.liked) {
            ivLike.setImageResource(R.mipmap.detail_like)
        } else {
            ivLike.setImageResource(R.mipmap.detail_unlike)
        }
        tvLike.text = if (post.likeNumbers == 0) "" else post.likeNumbers.toString()

        ivLike.trackData(
            page = SpmPageDef.SingleDetailRoute,
            onlyHit = true,
            traceInfo = post.traceInfo,
            element = SpmElementDef.postDetailLike,
            params = SpmTrackHandler.trackPostMap(
                position,
                post.toJson().toBean<PostD>(),
            )
                .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                .plus("result" to if (post.liked) "0" else "1")
        )
        ivLike.click {//点赞
            CommonMutateManage.likePost(
                activity,
                post.id,
                post.contentType,
                post.posterInfo.poster.id,
                post.liked,
                post.likeNumbers,
                {
                    PostDetailHelp.changeLikeState(
                        !post.liked,
                        if (!post.liked) post.likeNumbers + 1 else post.likeNumbers - 1,
                        ivLike, tvLike
                    )
                }) { like, count ->
                ApolloValSetExt.setApolloVal<PicPost>(post, "liked", like)
                ApolloValSetExt.setApolloVal<PicPost>(post, "likeNumbers", count)
                PostDetailHelp.changeLikeState(
                    like, count,
                    ivLike, tvLike
                )
            }
        }
        ivComment.click {//评论
            CommentPostListDialog(
                activity,
                post.id, post.contentType ?: "1", post.commentCount
            ) {
                ApolloValSetExt.setApolloVal<PicPost>(post, "commentCount", post.commentCount + 1)
                tvComment.text = post.commentCount.toString()
            }.show(activity.supportFragmentManager, "comment")
        }
    }

    /**
     * 获取挂载商品
     */
    private fun showMountedProduct(
        post: PicPost,
        llProduct: LinearLayout,
        recycler: RecyclerView,
    ) {

        var productList: ArrayList<ProductF> = arrayListOf()//挂载商品

        val mAdapter: MutableAdapter by lazyOnNone {
            MutableAdapter(productList).apply {
                addVhDelegate {
                    MountedProductHolder(
                        ItemMountProductBinding.inflate(it.inflater, it, false), activity
                    )
                }
            }
        }
        if (post.productList != null && post.productList!!.isNotEmpty()) {
            for (i in post.productList?.indices!!) {
                val item = post.productList!![i]
                if (i < 5) {
                    productList.add(item.productF)
                }
//            for (item in post.productList!!) {
//                productList.add(item.productF)
//            }
            }
        }

        llProduct.visibleOrGone(productList.isNotEmpty()) {
            recycler.layoutManager =
                LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)

            if (recycler.itemDecorationCount === 0) {
                recycler.addItemDecoration(
                    SpaceItemDecoration.newHorizontalDecoration(CommUtils.dip2px(5))
                )
            }
            recycler.adapter = mAdapter
            mAdapter.notifyDataSetChanged()
        }
    }


    private fun setListener(post: PicPost, position: Int) {
        binding.tvFollow.setOnClickListener {//关注
            CommonMutateManage.followUser(
                activity,
                post.posterInfo.poster.id,
                post.posterInfo.poster.relationCode,
                {
                    setFollowState(if (!PostUtils.followed(post.posterInfo.poster.relationCode)) UserRelationCodeEnum.FOLLOW.ordinal else UserRelationCodeEnum.NOTHING.ordinal)
                }) { state ->

                ApolloValSetExt.setApolloVal<Poster>(
                    post.posterInfo.poster,
                    "relationCode",
                    state
                )
                setFollowState(state)
            }
        }
        binding.ivShare.setOnClickListener {//分享
            var productStr = PostDetailHelp.getShareProductListString(post.productList)
            Log.e("PostDetailHelp", "=====$productStr")
            ShareDialog(
                activity,
                "${ShareUrlUtils().getUrl(ShareTypeEnum.PIC_POST)}${post.id}&type=1&productList=$productStr&countryCode=${UserDataCenter.getLocalCountryCode()}",
                shareCome = ShareTypeEnum.PIC_POST
            ) {
//                shareCallBack.invoke()
            }.show(activity.supportFragmentManager, "share")

            AppsflyerManager.reportContentShare(
                mapOf(
                    "af_content_id" to post.id,
                    "af_content_type" to (post.contentType ?: "1"),
                )
            )
        }

        binding.ivImgSearch.run {
            trackData(
                page = SpmPageDef.SingleDetailRoute,
                element = SpmElementDef.ImageRecognition,
                traceInfo = post.traceInfo,
                onlyHit = true,
                params = SpmTrackHandler.trackPostMap(
                    position,
                    post.toJson().toBean<PostD>(),
                )
            )
            click {
                activity.navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                    withString(RoutePage.ImageSearch.ARGS_IMG_URL, currentImgUrl)
                    withString(
                        RoutePage.ImageSearch.ARG_POST_PIC_ID,
                        post.pictures?.get(0)?.pictureF?.id
                    )
                }
            }
        }
    }

    private fun setFollowState(relationCode: Int) {
        if (PostUtils.followed(relationCode)) {
            binding.tvFollow.setImageResource(com.starblink.basic.style.R.mipmap.icon_user_followed)
        } else {
            binding.tvFollow.setImageResource(com.starblink.basic.style.R.mipmap.icon_user_follow)
        }
    }

    private fun setLayoutSize(post: PicPost, position: Int) {
        var imgContainerH =
            (if (BarUtils.isNavBarVisible(activity)) appScreenHeight else screenHeight) - dp2px(150f + 10f - 30f)
        if (post.productList != null && post.productList!!.isNotEmpty()) {
            imgContainerH -= 74.dp
        }
        if (position < 3 && hasNext) {
            imgContainerH -= 76.dp//存在引导
        }

        binding.banner.updateLayoutParams {
            width = ViewGroup.LayoutParams.MATCH_PARENT
            height = imgContainerH
        }
        val list: List<String> = post.pictures?.map { it.pictureF.picUrl } ?: listOf()

        binding.banner.run {
            binding.banner//添加生命周期观察者
                .setAdapter(
                    ProductImgAdapter(
                        list,
                        context,
                        post.mainPicSize,
                        imgContainerH, itemIndex = index,
                    ) {
                    }
                ).setLoopTime(4000)
                .isAutoLoop(true)
                .addOnPageChangeListener(object : OnPageChangeListener {
                    override fun onPageScrolled(
                        position: Int,
                        positionOffset: Float,
                        positionOffsetPixels: Int
                    ) {
                    }

                    override fun onPageSelected(pos: Int) {
                        if (post.pictures?.size ?: 0 > pos) {
                            currentImgUrl = list[pos]
                        }
                        binding.ivImgSearch.visibleOrGone(post.pictures?.get(pos)?.pictureF?.imageIdentifyFlag == true) {}
                        binding.ivImgSearch.setOnClickListener {
                            navigationTo(RoutePage.ImageSearch.PAGE_RESULT) {
                                withString(RoutePage.ImageSearch.ARGS_IMG_URL, currentImgUrl)
                                withString(
                                    RoutePage.ImageSearch.ARG_POST_PIC_ID,
                                    post.pictures?.get(pos)?.pictureF?.id
                                )
                            }
                        }
                    }

                    override fun onPageScrollStateChanged(state: Int) {
                    }
                })
                .setIndicatorMargins(
                    IndicatorConfig.Margins(
                        0,
                        0,
                        0,
                        50
                    )
                )
//                .setIndicatorWidth(dp2px(6f), dp2px(18f))
//                .setIndicatorHeight(dp2px(6f)).setIndicatorRadius(dp2px(6f))
                .setIndicatorSpace(dp2px(6f))
                .setIndicator(
                    GuangDrawableIndicator(
                        activity,
                    )
                )
        }
    }

}